package com.tao.com.xiaowen.module.me;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.tao.com.xiaowen.config.http.MyJson;
import com.tao.com.xiaowen.model.BmobUserAuth;
import com.tao.com.xiaowen.model.Model;
import com.tao.com.xiaowen.event.UserAuthEvent;
import com.tao.com.xiaowen.event.UserInfoEvent;
import com.tao.com.xiaowen.R;
import com.tao.com.xiaowen.config.tecent.BaseUiListener;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;

/**
 * Created by Administrator on 2016/8/5.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private Tencent tencent;
    private IUiListener listener;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private Boolean isRemember;

    private String emailSql;
    private String passwordSql;

    private ImageButton btnReturn;
    private TextView titleView;
    private Button qqLogin;

    private EditText userEmail;
    private EditText userPassword;
    private Button userRegister;
    private Button userLogin;
    private CheckBox rememberCb;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

//        Bmob.initialize(this, Model.APP_ID_BMOB);
        tencent = Tencent.createInstance(Model.APP_ID_QQ, this.getApplicationContext());

        initView();
    }

    private void initView() {
        btnReturn = (ImageButton) findViewById(R.id.return_button);
        titleView = (TextView) findViewById(R.id.title);
        qqLogin = (Button) findViewById(R.id.login_qq);
        userEmail = (EditText) findViewById(R.id.user_email);
        userPassword = (EditText) findViewById(R.id.user_password);
        userRegister = (Button) findViewById(R.id.user_register);
        userLogin = (Button) findViewById(R.id.user_login);
        rememberCb = (CheckBox) findViewById(R.id.remember_password);

        btnReturn.setOnClickListener(this);
        qqLogin.setOnClickListener(this);
        userRegister.setOnClickListener(this);
        userLogin.setOnClickListener(this);

        titleView.setText(R.string.login);

        sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        isRemember = sharedPreferences.getBoolean("remember_password", false);
        emailSql = sharedPreferences.getString("email", "");
        passwordSql = sharedPreferences.getString("password", "");

        if (isRemember) {
            userEmail.setText(emailSql);
            userPassword.setText(passwordSql);
            rememberCb.setChecked(true);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_button:
                finish();
                break;
            case R.id.login_qq:
                qqLogin();
                break;
            case R.id.user_register:
                userRegister();
                break;
            case R.id.user_login:
                userLogin();
                break;
            default:
                break;
        }
    }

    private void userRegister() {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);

    }

    private void userLogin() {
        final String email = String.valueOf(userEmail.getText());
        final String password = String.valueOf(userPassword.getText());

        BmobUser.loginByAccount(email, password, new LogInListener<Object>() {
            @Override
            public void done(Object o, BmobException e) {
                if (o != null) {
                    Object jsonData = BmobUser.getObjectByKey("emailVerified");
                    String emailVd = jsonData.toString();
                    if (emailVd.equals("true")) {
                        Toast.makeText(LoginActivity.this, "用户登陆成功!", Toast.LENGTH_SHORT).show();
                        editor = sharedPreferences.edit();
                        if (rememberCb.isChecked()) {
                            editor.putBoolean("remember_password", true);
                        } else {
                            editor.clear();
                        }
                        if ((TextUtils.isEmpty(emailSql) && TextUtils.isEmpty(passwordSql)) || (emailSql.equals(email) && passwordSql.equals(password))) {
                            editor.putString("email", email);
                            editor.putString("password", password);
                        }
                        editor.commit();
                        EventBus.getDefault().post(new UserAuthEvent());
                        finish();
                    } else if (emailVd.equals("false")) {
                        Toast.makeText(LoginActivity.this, "请到邮箱内进行验证!", Toast.LENGTH_SHORT).show();
                    } else if (emailVd.equals("miss")) {
                        Toast.makeText(LoginActivity.this, "该邮箱并不存在!", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(LoginActivity.this, "失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void qqLogin() {
        listener = new BaseUiListener() {
            @Override
            public void onComplete(final Object o) {
                super.onComplete(o);
                BmobUserAuth userAuth = MyJson.getUserAuth(o);
                String access_token = userAuth.getAccess_token();
                String expires_in = userAuth.getExpires_in();
                String openid = userAuth.getOpenid();
                BmobUser.loginWithAuthData(new BmobUserAuth(Model.SNS_TYPE_QQ, access_token, expires_in, openid), new LogInListener<JSONObject>() {
                    @Override
                    public void done(JSONObject jsonObject, BmobException e) {
                        EventBus.getDefault().post(new UserInfoEvent());
                        finish();
                    }
                });
            }
        };
        if (!tencent.isSessionValid()) {
            tencent.login(this, Model.SCOPE, listener);
        } else if (tencent.isSessionValid()) {
            tencent.logout(this);
            tencent.login(this, Model.SCOPE, listener);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, listener);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
